const fs = require('fs');
const path = require('path');
const Pinyin = require("pinyin");
// 定义一个函数来递归地读取文件夹中的所有文件，并过滤出 .json 文件
function readJsonFiles(dir) {
  let fileList = [];

  const files = fs.readdirSync(dir, { withFileTypes: true });
  files.forEach(file => {
    if (file.isDirectory()) {
      // 如果是文件夹，则递归调用
      fileList = fileList.concat(readJsonFiles(path.join(dir, file.name)));
    } else if (file.name.endsWith('.json')) {
      // 如果是 .json 文件，则添加到文件列表中
      fileList.push(file.name.replace('.json', ''));
    }
  });

  return fileList;
}

// 使用示例
const directoryPath = 'D:\\work\\bishun_data'; // 替换为你的文件夹路径
// const jsonFiles = readJsonFiles(directoryPath);

// // 将 .json 文件的文件名写入到 name.json 文件中
// const outputFilePath = path.join(directoryPath, 'name.json');
// fs.writeFileSync(outputFilePath, JSON.stringify(jsonFiles, null, 2));

// console.log(`JSON file names have been written to ${outputFilePath}`);
function updateJsonFiles() {
  const buxianJsonStr = fs.readFileSync(path.join(directoryPath, 'author', 'buxian.json'), { encoding: 'utf-8'});
  const buxianJson = JSON.parse(buxianJsonStr);
  buxianJson.forEach(item => {
    item.id = item.url.replace('https://www.gushiwen.cn/','').replace('.aspx','')
  })
  fs.writeFileSync(path.join(directoryPath, 'author', 'buxian.json'), JSON.stringify(buxianJson))
  const files = fs.readdirSync(path.join(directoryPath, 'author'), { withFileTypes: true });
  files.forEach(file => {
    if (file.name.endsWith('buxian.json')) {
    }
    if (file.name.endsWith('.json')) {
      // 如果是 .json 文件，则添加到文件列表中
      const jsonStr = fs.readFileSync(path.join(file.path, file.name), { encoding: 'utf-8'});
      const json = JSON.parse(jsonStr)
      const dynasty = file.name.replace('.json', '');
      json.forEach(item => {
        const id = item.url.replace('https://www.gushiwen.cn/','').replace('.aspx','');
        item.id = id;
        item.dynasty = dynasty;
        fs.writeFileSync(path.join(directoryPath, 'author_detail_list', id + '.json'), JSON.stringify(item))
      });
      fs.writeFileSync(path.join(file.path, file.name), JSON.stringify(json))
    }
  });
}

// updateJsonFiles()

function updateAuthorByList() {
  const files = fs.readdirSync(path.join(directoryPath, 'author'), { withFileTypes: true });
  files.forEach(file => {
    if (file.name.endsWith('.json')) {
      // 如果是 .json 文件，则添加到文件列表中
      const jsonStr = fs.readFileSync(path.join(file.path, file.name), { encoding: 'utf-8'});
      const json = JSON.parse(jsonStr)
      json.forEach(item => {
        const id = item.url.replace('https://www.gushiwen.cn/','').replace('.aspx','');
        delete item.url;
        const detailJsonStr = fs.readFileSync(path.join(directoryPath, 'author_detail', id + '.json'), { encoding: 'utf-8' });
        const detailJson = JSON.parse(detailJsonStr);
        item.imgUrl = detailJson.imgUrl;
        item.dynasty = detailJson.dynasty;
        if (detailJson.info) {
          item.info = detailJson.info.slice(0, 60) + '...';
        }
      });
      fs.writeFileSync(path.join(directoryPath, 'author_list', file.name), JSON.stringify(json))
    }
  });
}
function updateAuthorList() {
  const files = fs.readdirSync(path.join(directoryPath, 'author'), { withFileTypes: true });
  files.forEach(file => {
    if (file.name.endsWith('.json')) {
      // 如果是 .json 文件，则添加到文件列表中
      const jsonStr = fs.readFileSync(path.join(file.path, file.name), { encoding: 'utf-8'});
      const json = JSON.parse(jsonStr)
      const dynasty = file.name.replace('.json', '');
      json.forEach(item => {
        const id = item.url.replace('https://www.gushiwen.cn/','').replace('.aspx','');
        item.id = id;
        item.dynasty = dynasty;
        delete item.url;
        // 查详情
        const detailJsonStr = fs.readFileSync(path.join(directoryPath, 'author_detail_list', id + '.json'), { encoding: 'utf-8'});
        const detailJson = JSON.parse(detailJsonStr);
        item.imgUrl = detailJson.imgUrl;
        if (detailJson.info) {
          item.info = detailJson.info.slice(0, 60);
        }
      });
      fs.writeFileSync(path.join(directoryPath, 'author_list', file.name), JSON.stringify(json))
    }
  });
}

// updateAuthorByList()

function updateHanziType() {
  const rjJsonStr = fs.readFileSync(path.join(directoryPath, 'rj.json'), { encoding: 'utf-8'});
  const rjJson = JSON.parse(rjJsonStr);
  rjJson.data.forEach(item => {
    item.contents = item.contents[0].split('');
  });
  fs.writeFileSync(path.join(directoryPath, 'rj.json'), JSON.stringify(rjJson));

  const sjJsonStr = fs.readFileSync(path.join(directoryPath, 'sj.json'), { encoding: 'utf-8'});
  const sjJson = JSON.parse(sjJsonStr);
  sjJson.data.forEach(item => {
    item.contents = item.contents[0].split('');
  });
  fs.writeFileSync(path.join(directoryPath, 'sj.json'), JSON.stringify(sjJson));


  const bsdJsonStr = fs.readFileSync(path.join(directoryPath, 'bsd.json'), { encoding: 'utf-8'});
  const bsdJson = JSON.parse(bsdJsonStr);
  bsdJson.data.forEach(item => {
    if (item.categories.length > 0) {
      item.categories.forEach(sub => {
        sub.contents = sub.contents[0].split('');
      });
    }
  });
  fs.writeFileSync(path.join(directoryPath, 'bsd.json'), JSON.stringify(bsdJson));
}

// updateHanziType()

function genPoemListByAuthor() {
  const files = fs.readdirSync(path.join(directoryPath, 'author_detail'), { withFileTypes: true });
  const poems = [];
  files.forEach(file => {
    if (file.name.endsWith('.json')) {
      const jsonStr = fs.readFileSync(path.join(file.path, file.name), { encoding: 'utf-8'});
      const json = JSON.parse(jsonStr)
      if (json.poems && json.poems.length > 0) {
        json.poems.forEach(item => {
          poems.push({
            ...item,
            author: {
              id: json.id,
              name: json.name,
              imgUrl: json.imgUrl
            }
          });
        });
      }
    }
  });
  fs.writeFileSync(path.join(directoryPath, 'poems.json'), JSON.stringify(poems))
}

// genPoemListByAuthor()
// updateAuthorList()

function generatePoemType() {
  const jsonStr = fs.readFileSync(path.join(directoryPath, 'poem_types.json'), { encoding: 'utf-8'});
  const json = JSON.parse(jsonStr)
  const jsonStr3 = fs.readFileSync(path.join('D:\\sonList.json'), { encoding: 'utf-8'});
  const json3 = JSON.parse(jsonStr3)
  const list = json3.reduce((a, c) => a.concat(c.scInfos), [])
  console.log(new Set(list.map(item => item.name)).size)
  // const arr = [];
  // json.forEach(item => {
  //   console.log(item.name, json2.some(it => it.name === item.name))
  //   if (!json2.some(it => item.name.includes(it.name))) {
  //     arr.push(item)
  //   }
  //   // const results = Pinyin.pinyin(item.name, { mode: 'normal', style: 'normal'});
  //   // item.id = results.reduce((a, c) => a.concat(c), []).join('');
  //   // console.log(item.name, item.id)
  //   // fs.mkdirSync(path.join(directoryPath, 'poem_list', item.name))
  // });
  // fs.writeFileSync(path.join(directoryPath, 'poem_typex.json'), JSON.stringify(arr))
}

// generatePoemType()

function computedPoemListLength() {
  const jsonStr = fs.readFileSync(path.join(directoryPath, 'poems.json'), { encoding: 'utf-8'});
  const json = JSON.parse(jsonStr)
  console.log('length:' + json.length)
}

// computedPoemListLength()


function generatePoemTypex() {
  const jsonStr = fs.readFileSync(path.join(directoryPath, 'poem_types.json'), { encoding: 'utf-8'});
  const json = JSON.parse(jsonStr)
  const jsonStr2 = fs.readFileSync(path.join(directoryPath, 'poem_typex.json'), { encoding: 'utf-8'});
  const json2 = JSON.parse(jsonStr2);

  json.forEach(item => {
    item.id = item.url.split('/').pop().replace('.aspx', '');
  });
  json2.forEach(item => {
    const results = Pinyin.pinyin(item.name.slice(-2), { mode: 'normal', style: 'normal'});
    item.id = results.reduce((a, c) => a.concat(c), []).join('');
    json.push(item);
  });
  fs.writeFileSync(path.join(directoryPath, 'poem_type_final.json'), JSON.stringify(json))
}

// generatePoemTypex()

function updatePoemByType() {
  const files = fs.readdirSync(path.join(directoryPath, 'poem_type'), { withFileTypes: true });
  const notFoundList = []
  files.forEach(file => {
    if (file.name.endsWith('.json')) {
      const jsonStr = fs.readFileSync(path.join(file.path, file.name), { encoding: 'utf-8'});
      const json = JSON.parse(jsonStr);
      json.forEach(item => {
        const tags = {
          id: file.name.replace('.json', ''),
          name: item.name.split(',')[0]
        };
        item.scInfos.forEach(poem => {
          const fileName = poem.url.split('/').pop().replace('.aspx', '.json');
          try {
            const poemStr = fs.readFileSync(path.join(directoryPath, 'poem_detail', fileName), { encoding: 'utf-8'});
            const poemJson = JSON.parse(poemStr);
            poemJson.tags = poemJson.tags ? poemJson.tags.concat(tags) : tags;

            poem.id = poemJson.id;
            // delete poem.url;
          } catch(e) {
            // console.log(poem)
            poem.id = poem.url.split('/').pop().replace('.aspx', '');
            notFoundList.push(poem)
          }
        });
      });
      fs.writeFileSync(path.join(directoryPath, 'notFoundList.json'), JSON.stringify(notFoundList));
    }
  });
}
// updatePoemByType()

function update2() {
  const names = [];
  const files = fs.readdirSync(path.join(directoryPath, 'author_list'), { withFileTypes: true });
  files.forEach(file => {
    if (file.name.endsWith('.json') && !file.name.includes('index.json')) {
      const name = file.name.replace('.json', '');
      names.push({
        id: Pinyin.pinyin(name, { mode: 'normal', style: 'normal'}).reduce((a, c) => a.concat(c), []).join(''),
        name,
        no: 1
      })
      fs.writeFileSync(path.join(directoryPath, 'author_list', 'index.json'), JSON.stringify(names));
    }
  });
}
// update2()

function update3() {
  const names = [];
  const files = fs.readdirSync(path.join(directoryPath, 'author_list'), { withFileTypes: true });
  files.forEach(file => {
    if (file.name.endsWith('.json') && !file.name.includes('index.json')) {
      const name = file.name.replace('.json', '');
      const pinyin = Pinyin.pinyin(name, { mode: 'normal', style: 'normal'}).reduce((a, c) => a.concat(c), []).join('');
      
      const poems = [];
      const jsonStr = fs.readFileSync(path.join(file.path, file.name), { encoding: 'utf-8'});
      const json = JSON.parse(jsonStr);
      json.forEach(item => {
        const authorJsonStr = fs.readFileSync(path.join(directoryPath, 'author_detail', item.id + '.json'), { encoding: 'utf-8'});
        const authorJson = JSON.parse(authorJsonStr);
        if (authorJson.poems) {
          poems.push(...authorJson.poems.map(it => {
            return {
              ...it,
              name: it.name + '(' + authorJson.name + ')'
            };
          }))
        }
      });

      // 每10个存一个文件
      const count = Math.ceil(poems.length / 10);
      for(let i = 1; i <= count; i++) {
        const fileName = pinyin + '_' + i + '_' + count + '.json';
        const data = {
          code: 0,
          message: "success",
          data: poems.slice((i - 1) * 10, i * 10)
        };
        fs.writeFileSync(path.join(directoryPath, 'poem_list_by_dynasty', fileName), JSON.stringify(data));
      }
    }
  });
}
update3()
